<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100">
        <el-form-item label="汇总方式" prop="timeType">
          <el-radio-group @change="groupChange" v-model="queryParams.timeType" size="large">
            <el-radio-button
              v-for="(item, index) in dataList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="统计日期" prop="timeScopes">
          <!-- <el-input v-noSpace v-model="queryParams.name" placeholder="请输入名字" /> -->
          <el-date-picker
            v-model="timeScopes"
            type="daterange"
            @change="validateYearRange"
            clearable
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <!-- <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请输入类型" style="width: 250px">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSeach">查询</el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
          <el-button
            type="success"
            @click="downloadTable"
            class="!rounded-button whitespace-nowrap"
            v-hasPerm="'sys:salesOrder:exp'"
          >
            <el-icon class="mr-1"><Download /></el-icon>
            导出报表
          </el-button>
          <el-button
            type="info"
            @click="HistoryClick"
            class="!rounded-button whitespace-nowrap"
            v-hasPerm="'sys:salesOrder:down'"
          >
            <el-icon class="mr-1"><Document /></el-icon>
            历史报表下载
          </el-button>
          <el-radio-group @change="handleTabClick" class="ml-3" v-model="activeTab" size="large">
            <el-radio-button
              v-for="(item, index) in activeList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="p0">
      <div v-show="activeTab == 1">
        <el-table
          height="700px"
          id="educe-table"
          v-loading="loading"
          show-overflow-tooltip
          :tooltip-formatter="tableRowFormatter"
          :data="tableData"
        >
          <el-table-column prop="time" label="统计日期" />
          <el-table-column prop="orderCount" label="订单数量" />
          <el-table-column prop="totalAmount" label="总销售额">
            <template #default="scope">
              <span class="font-medium">
                ￥{{ (scope.row.totalAmount || 0.0).toLocaleString() }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="discountAmount" label="折扣金额">
            <template #default="scope">
              <span class="font-medium">
                ￥{{ (scope.row.discountAmount || 0.0).toLocaleString() }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="refundCount" label="退货数量" />
          <el-table-column prop="returnAmount" label="退货金额">
            <template #default="scope">
              <span class="font-medium">
                ￥{{ (scope.row.returnAmount || 0.0).toLocaleString() }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="activeTab == 2">
        <div class="rounded-lg w-full bg-white p-6 shadow-sm mt-8">
          <div class="mb-4 flex items-center justify-between">
            <div class="text-lg font-medium">销售趋势分析</div>
            <el-radio-group
              @change="statisticsClick"
              class="ml-3"
              v-model="statisticsTab"
              size="large"
            >
              <el-radio-button
                v-for="(item, index) in statisticsList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-radio-group>
          </div>
          <div ref="chartRef" style="width: 100%" class="h-[400px] w-full"></div>
        </div>
      </div>
    </el-card>
    <!-- 历史报表下载弹窗 -->
    <el-dialog v-model="historyDialogVisible" title="历史报表下载" width="600px">
      <el-table :data="historyReports" style="width: 100%">
        <el-table-column prop="fileName" label="文件名称" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button @click="historyDownLoad(row.filePath, row.fileName)" type="primary" link>
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-model:total="peportTotal"
        v-model:page="reportParams.pageNum"
        v-model:limit="reportParams.pageSize"
        @pagination="reportHistoryList"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { tableRowFormatter } from "@/utils/index";
import { ref, onMounted, watch } from "vue";
import { FormItemRule } from "element-plus/es";
import type { EChartsOption } from "echarts";
import * as echarts from "echarts";
import statementApi, {
  CustomerReportPageQuery,
  locationPageQuery,
} from "@/api/statement/statement";
import { useDateRanges } from "@/utils/useDateRanges";
import * as XLSX from "xlsx-js-style";

import { downLoad, historyDownLoad } from "@/utils/downLoad";
const historyDialogVisible = ref(false);
const reportType = 2;
const reportName = "销售订单报表";
const historyReports = ref([]);
const peportTotal = ref(0);
const reportParams: locationPageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  reportType: reportType,
});
const reportHistoryList = () => {
  statementApi
    .getReportHistory(reportParams)
    .then((data) => {
      console.log(data);
      historyReports.value = [...(data.list as never)];
      historyReports.value.forEach((item: any) => {
        item.fileName = reportName + "_" + useDateRanges().getDate() + ".xlsx";
      });
      peportTotal.value = data.total;
    })
    .finally(() => {});
};
const HistoryClick = async () => {
  historyDialogVisible.value = true;
  reportHistoryList();
};
//下载表格
const downloadTable = () => {
  downLoad(queryParams, reportType, reportName);
};

const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts;
const timeScopes = ref([]);
const groupChange = () => {
  timeScopes.value = [];
};
// 限制选择范围不超过365天
const validateYearRange = (val: any) => {
  if (!val || val.length !== 2) {
    return;
  }

  console.log(queryParams.timeType);
  if (!queryParams.timeType) return ElMessage.error(`请先选择汇总方式`), (timeScopes.value = []);
  if (queryParams.timeType != "day") return;
  const [start, end] = val;
  const startDate = new Date(start);
  const endDate = new Date(end);

  // 计算两个日期之间的年份差
  const yearDiff = endDate.getFullYear() - startDate.getFullYear();
  const monthDiff = endDate.getMonth() - startDate.getMonth();
  const dayDiff = endDate.getDate() - startDate.getDate();

  // 如果年份差大于1年，或者正好1年但结束月份/日期大于开始月份/日期
  if (yearDiff > 1 || (yearDiff === 1 && (monthDiff > 0 || (monthDiff === 0 && dayDiff > 0)))) {
    ElMessage.error(`选择的时间范围不能超过一年`);

    timeScopes.value = [];
  }
};
const handleTabClick = () => {
  nextTick(() => {
    chart?.resize();
  });
};
const activeList = ref([
  { label: "报表", value: 1 },
  { label: "统计图", value: 2 },
]);
const statisticsList = ref([
  { label: "数量统计", value: 1 },
  { label: "金额统计", value: 2 },
]);
const activeTab = ref(1);
const statisticsTab = ref(1);

// 日期
const dataList = ref([
  { label: "天", value: "day" },
  { label: "周", value: "week" },
  { label: "月", value: "month" },
  { label: "季度", value: "quarter" },
  { label: "年", value: "year" },
]);

let metrics = [
  { key: "orderCount", label: "订单数量" },
  { key: "refundCount", label: "退货数量" },
];
const selectedMetrics = ref(["orderCount", "refundCount"]);
const initChart = () => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value);
    updateChart();
  }
};
const statisticsClick = (val: any) => {
  console.log(val);
  if (val == 1) {
    metrics = [
      { key: "orderCount", label: "订单数量" },
      { key: "refundCount", label: "退货数量" },
    ];
    selectedMetrics.value = ["orderCount", "refundCount"];
  } else {
    metrics = [
      { key: "totalAmount", label: "总销售额" },
      { key: "discountAmount", label: "折扣金额" },
      { key: "returnAmount", label: "退货金额" },
    ];
    selectedMetrics.value = ["totalAmount", "discountAmount", "returnAmount"];
  }
  updateChart();
};
const updateChart = () => {
  const dates = tableData.value.map((item: any) => item.time);
  console.log(tableData, "tableData");

  const option: EChartsOption = {
    animation: false,
    tooltip: {
      trigger: "axis",
      // formatter: (params: any) => {
      //   let result = `日期：${params[0].axisValue}<br/>`;
      //   params.forEach((item: any) => {
      //     let value = item.value;
      //     if (["总销售额", "折扣金额", "退货金额"].includes(item.seriesName)) {
      //       value = `¥${value || 0}`;
      //     }
      //     result += `${item.seriesName}: ${value}<br/>`;
      //   });
      //   return result;
      // },
    },

    legend: {
      data: metrics.filter((m) => selectedMetrics.value.includes(m.key)).map((m) => m.label),
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dates,
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        rotate: 45,
      },
    },
    yAxis: [
      {
        type: "value",
        name: statisticsTab.value == 1 ? "数量" : "金额",
        position: "left",
        axisLabel: {
          formatter: statisticsTab.value == 1 ? "{value}" : "¥{value}",
        },
      },
    ],
    series: selectedMetrics.value.map((metric) => {
      const metricInfo = metrics.find((m) => m.key === metric);
      return {
        name: metricInfo?.label,
        type: "line",
        smooth: true,
        // yAxisIndex: ["orderCount", "refundCount"].includes(metric) ? 0 : 1,
        data: tableData.value.map((item) => item[metric] || 0),
      };
    }),
  };
  chart.setOption(option, true);
};
// 加载loading
const loading = ref(false);
// 搜索ref
const queryFormRef = ref(ElForm);

const queryParams: CustomerReportPageQuery = reactive({
  timeType: "day",
});

const tableData = ref([]);
// 查询方法
const handleSeach = () => {
  loading.value = true;
  queryParams.startDate = timeScopes.value[0];
  queryParams.endDate = timeScopes.value[1];
  statementApi
    .getSalesOrderReport(queryParams)
    .then((data) => {
      tableData.value = [...(data as never)];
      updateChart();
    })
    .finally(() => {
      loading.value = false;
    });
};
// 重置方法
const handleReset = () => {
  queryFormRef.value.resetFields();
  timeScopes.value = [];
  tableData.value = [];
};

onMounted(() => {
  initChart();
  window.addEventListener("resize", () => {
    chart?.resize();
  });
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
.el-checkbox-button :deep(.el-checkbox-button__inner) {
  border-radius: 4px;
  margin-right: 8px;
  border: 1px solid #dcdfe6;
}
.el-checkbox-button.is-checked :deep(.el-checkbox-button__inner) {
  border-color: var(--el-color-primary);
}
:deep(.el-card__body) {
  padding: 0 20px !important;
}
</style>
